package com.soulmate.service.stock;

import com.soulmate.api.stock.StockService;
import com.soulmate.api.stock.dto.StockDTO;
import com.soulmate.dao.stock.StockDao;
import com.soulmate.dao.stock.data.Stock;
import com.soulmate.exception.BusinessException;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboService;

import java.util.Objects;

/**
 * 库存服务
 *
 * @author huaiping
 * @date 2/22/23-3:12 PM
 */
@Slf4j
@DubboService
@AllArgsConstructor
public class StockServiceImpl implements StockService {
    private StockDao stockDao;

    @Override
    public StockDTO deduct(Long productId, Integer deductCount) throws BusinessException {
        // 查询商品库存
        Stock stock = stockDao.selectByProductId(productId);
        if (Objects.isNull(stock)) {
            String errMsg = String.format("商品: %s信息不存在", productId);
            log.error(errMsg);
            throw new BusinessException(errMsg, 404);
        }
        // 判断库存
        if (stock.getProductCount() < deductCount) {
            String errMsg = String.format("商品: %d库存不足, 现有库存%d，扣除%d", productId, stock.getProductCount(),
                    deductCount);
            log.error(errMsg);
            throw new BusinessException(errMsg, 403);
        }
        // 扣除库存
        // 可能扣除失败，这里需要加入重试机制
        stockDao.updateByProductId(productId, stock.getProductCount() - deductCount, stock.getVersion());
        Stock updateStock = stockDao.selectById(stock.getId());
        return new StockDTO(updateStock.getId(), updateStock.getProductId(), updateStock.getProductCount());
    }
}
